package com.DosonLeung.homeschoolcommunication.Controllers;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.animation.RotateAnimation;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.DosonLeung.homeschoolcommunication.Constant.SystemConstant;
import com.DosonLeung.homeschoolcommunication.Constant.UserConstant;
import com.DosonLeung.homeschoolcommunication.Models.UserModel;
import com.DosonLeung.homeschoolcommunication.Modules.SystemAlbumModule.SystemAlbumActivity;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.Utils.ImageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.NetWorkUtil;
import com.DosonLeung.homeschoolcommunication.Utils.StorageUtil;
import com.DosonLeung.homeschoolcommunication.Utils.UpdataUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;


/**
 * Created by DosonLeung on 2014/11/12.
 */
public class RegistActivity extends Activity {

    Activity self = this;
    Handler mHandler;
    ProgressDialog pd;
    UserModel.register register;

    //注册页面
    LinearLayout step1;
    LinearLayout step2;
    LinearLayout step3forPatriarch;
    LinearLayout step3forTeacher;
    //注册页面1的组件
    ImageView choosePatriarch;
    ImageView chooseTeacher;
    ImageView submitRole;
    //注册页面2的组件
    TextView step2Title;
    EditText editAccount;
    EditText editPassword;
    EditText verifyPassword;
    EditText verificationInput;
    TextView getVerification;
    ImageView submitInfo;
    View checkIfRegistedLabel;
    View checkIfRepasswordLabel;
    //注册页面3(家长版)的组件
    ImageView editPMyIcon;
    EditText editPName;
    TextView pChooseMan;
    TextView pChooseWoman;
    EditText editPGuardian;
    EditText editPContact;
    EditText editPChildName;
    EditText editPChildSchool;
    Spinner spinnerPChildClass;
    ImageView editPChildIcon;
    ImageView submitPDetail;
    TextView step3PTitle;
    //注册页面3（老师版）的组件
    ImageView editTMyIcon;
    EditText editTName;
    TextView tChooseMan;
    TextView tChooseWoman;
    EditText editTPost;
    EditText editTContact;
    EditText editTSchool;
    Spinner spinnerTSubject;
    Spinner spinnerTClass;
    ImageView submitTDetail;
    TextView step3TTitle;
    //选择班级的下拉列表适配器
    BaseAdapter baseAdapter;
    //旋转的动画效果
    RotateAnimation spin;
    //选择对象，家长false,老师true
    private boolean chooseTarget = false;
    //选择对象，先生false,女士true
    private boolean chooseSalutation = false;
    //验证码四位
    private String verifyCode = "";
    //班级的id
    private ArrayList<String> cids = new ArrayList<String>();
    //科目的id
    private ArrayList<String> sids = new ArrayList<String>();
    //用户·选择的cid
    private String cid;
    //用户选择的sid
    private String sid = "";
    // 从相册返回的图片路径
    private String url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.regist_activity);
        initTab();
        initWidgets();
        initHandler();
        //获取注册账号对象
        register = new UserModel().getRegister(mHandler);
    }

    private void initTab() {
        step1 = (LinearLayout) findViewById(R.id.regist_step1);
        step2 = (LinearLayout) findViewById(R.id.regist_step2);
        step3forPatriarch = (LinearLayout) findViewById(R.id.p_regist_step3);
        step3forTeacher = (LinearLayout) findViewById(R.id.t_regist_step3);
        step1.setVisibility(View.VISIBLE);
        step2.setVisibility(View.GONE);
        step3forPatriarch.setVisibility(View.GONE);
        step3forTeacher.setVisibility(View.GONE);
    }

    private void initWidgets() {
        //注册页面1的组件
        choosePatriarch = (ImageView) findViewById(R.id.choose_patriarch);
        chooseTeacher = (ImageView) findViewById(R.id.choose_teacher);
        submitRole = (ImageView) findViewById(R.id.step1_submit);
        //注册页面2的组件
        step2Title = (TextView) findViewById(R.id.step2_title);
        editAccount = (EditText) findViewById(R.id.step2_account);
        editPassword = (EditText) findViewById(R.id.step2_password);
        verifyPassword = (EditText) findViewById(R.id.step2_repassword);
//        getVerification = (TextView) findViewById(R.id.step2_get_verification);
//        verificationInput = (EditText) findViewById(R.id.step2_verification_input);
        submitInfo = (ImageView) findViewById(R.id.step2_submit);
        checkIfRegistedLabel = findViewById(R.id.check_if_regist_label);
        checkIfRepasswordLabel = findViewById(R.id.check_if_repassword_label);
        editPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        verifyPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        //注册页面3(家长版)的组件
        editPMyIcon = (ImageView) findViewById(R.id.p_step3_setting_myicon);
        editPName = (EditText) findViewById(R.id.p_step3_setting_name);
        pChooseMan = (TextView) findViewById(R.id.p_choose_gentlemen);
        pChooseWoman = (TextView) findViewById(R.id.p_choose_lady);
        editPGuardian = (EditText) findViewById(R.id.p_step3_setting_guardian);
        editPContact = (EditText) findViewById(R.id.p_step3_setting_contact);
        editPChildName = (EditText) findViewById(R.id.p_step3_setting_childname);
        editPChildSchool = (EditText) findViewById(R.id.p_step3_setting_school);
        spinnerPChildClass = (Spinner) findViewById(R.id.p_step3_setting_class);
        editPChildIcon = (ImageView) findViewById(R.id.p_step3_setting_childicon);
        submitPDetail = (ImageView) findViewById(R.id.p_step3_submit);
        step3PTitle = (TextView) findViewById(R.id.p_step3_title);
        //注册页面3（老师版）的组件
        editTMyIcon = (ImageView) findViewById(R.id.t_step3_setting_myicon);
        editTName = (EditText) findViewById(R.id.t_step3_setting_name);
        tChooseMan = (TextView) findViewById(R.id.t_choose_gentlemen);
        tChooseWoman = (TextView) findViewById(R.id.t_choose_lady);
        editTPost = (EditText) findViewById(R.id.t_step3_setting_post);//角色
        editTContact = (EditText) findViewById(R.id.t_step3_setting_contact);
        editTSchool = (EditText) findViewById(R.id.t_step3_setting_school);//联系方式
        spinnerTClass = (Spinner) findViewById(R.id.t_step3_setting_class);//所属班级
        spinnerTSubject = (Spinner) findViewById(R.id.t_step3_setting_subject);
        submitTDetail = (ImageView) findViewById(R.id.t_step3_submit);
        step3TTitle = (TextView) findViewById(R.id.t_step3_title);
        //注册事件
        choosePatriarch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressChoosePatriarch(v);
            }
        });
        chooseTeacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressChooseTeacher(v);
            }
        });
        submitRole.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressSubmitRole(v);
            }
        });
        editAccount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                chechIfRegisted();
            }
        });
        verifyPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                passwordMatch();
            }
        });
        editPMyIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressMyIcon(v);
            }
        });
        editTMyIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressMyIcon(v);
            }
        });
        pChooseMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressChooseMan(view);
            }
        });
        pChooseWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressChooseWomen(view);
            }
        });

        tChooseMan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressChooseMan(view);
            }
        });
        tChooseWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressChooseWomen(view);
            }
        });

        submitInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressSubmitInfo(v);
            }
        });
        submitPDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressSubmitPDetail(v);
            }
        });
        submitTDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pressSubmitTDetail(v);
            }
        });
    }

    private void initHandler() {

        /*
        * 0x100 检验账号是否已注册中
        * 0x200 提交注册信息成功
        * 0x300 开始菊花
        * 0x401 提交注册信息 server return error
        * 0x404 提交注册信息 server return null或者检查账号是否被注册失败 或者获取班级列表失败
        * 0x402 检查账号是否被注册返回成功
        * 0x403 检查账号是否被注册返回失败
        * 0x405 获取班级列表成功
        * 0x408 获取科目列表成功
        * 0x500 检查完毕
        * 0x502 上传成功
        * 0x504 上传失败
        */
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0x100:
                        checkIfRegistedLabel.setVisibility(View.VISIBLE);
                        break;
                    case 0x200://提交成功
                        stopReflashDialog();
                        register.save();
                        register.updateUserConstant();
                        Toast.makeText(self, "注册成功！", Toast.LENGTH_SHORT).show();
                        Intent intent = RegistActivity.this.getIntent();
                        intent.putExtra("regist", true);
                        RegistActivity.this.setResult(0, intent);
                        RegistActivity.this.finish();
                        break;
                    case 0x300:
                        showMum("点击取消上传");
                        break;
                    case 0x401:
                        stopReflashDialog();
                        Toast.makeText(self, "注册失败！", Toast.LENGTH_LONG).show();
                        break;
                    case 0x404:
                        stopReflashDialog();
                        Toast.makeText(self, "网络超时", Toast.LENGTH_LONG).show();
                        break;
                    case 0x402:
                        checkIfRegistedLabel.setVisibility(View.VISIBLE);
                        step2Title.setText("账号可以使用");
                        break;
                    case 0x403:
                        checkIfRegistedLabel.setVisibility(View.GONE);
                        step2Title.setText("账号已经被使用");
                        break;
                    case 0x405:
                        stopReflashDialog();
                        initClassAdapter();
                        break;
                    case 0x408:
                        stopReflashDialog();
                        initSubjectAdapter();
                    case 0x500:
                        checkIfRegistedLabel.setVisibility(View.GONE);
                        spin(checkIfRegistedLabel, false);
                        break;
                    case SystemConstant.UPLOAD_IMAGE_SUCCESS:
                        stopReflashDialog();
                        Toast.makeText(self, "上传成功", Toast.LENGTH_SHORT).show();
                        break;
                    case SystemConstant.UPLOAD_IMAGE_FAIL:
                        stopReflashDialog();
                        Toast.makeText(self, "上传失败，网络超时", Toast.LENGTH_SHORT).show();
                        break;

                }
            }
        };
    }

    //初始化适配器
    private void initClassAdapter() {
        int length = UserConstant.CLASS_LIST.length();
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> item;
        JSONObject jsonObject = null;
        for (int position = 0; position < length; position++) {
            item = new HashMap<String, String>();
            try {
                jsonObject = UserConstant.CLASS_LIST.getJSONObject(position);
                cids.add(jsonObject.getString("cid"));
                String extra = "(" + jsonObject.getString("description") + ")";
                if (extra.length() > 2)
                    item.put("name", (jsonObject.getString("name") + extra));
                else
                    item.put("name", jsonObject.getString("name"));
                list.add(item);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        SimpleAdapter adapter = new SimpleAdapter(self, list, R.layout.spinner_item, new String[]{"name"}, new int[]{R.id.spinner_text});
        spinnerPChildClass.setAdapter(adapter);
        spinnerTClass.setAdapter(adapter);
        chooseClass();
    }

    //初始化适配器
    private void initSubjectAdapter() {
        int length = UserConstant.SUBJECTLIST.length();
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> item;
        JSONObject jsonObject = null;
        for (int position = 0; position < length; position++) {
            item = new HashMap<String, String>();
            try {
                jsonObject = UserConstant.SUBJECTLIST.getJSONObject(position);
                sids.add(jsonObject.getString("name"));
                String name = jsonObject.getString("name");
                item.put("name", name);
                list.add(item);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        SimpleAdapter adapter = new SimpleAdapter(self, list, R.layout.spinner_item, new String[]{"name"}, new int[]{R.id.spinner_text});
        spinnerTSubject.setAdapter(adapter);
        chooseSubject();
    }

    //页面一事件
    private void pressChoosePatriarch(View v) {
        register.setType("patriarch");
        chooseTarget = false;
        choosePatriarch.setImageResource(R.drawable.chose_patriarch);
        chooseTeacher.setImageResource(R.drawable.choose_teacher);
    }

    private void pressChooseTeacher(View v) {
        register.setRole("teacher");
        chooseTarget = true;
        choosePatriarch.setImageResource(R.drawable.choose_patriarch);
        chooseTeacher.setImageResource(R.drawable.chose_teacher);
    }

    private void pressSubmitRole(View v) {
        step1.setVisibility(View.GONE);
        step2.setVisibility(View.VISIBLE);
    }

    private void chechIfRegisted() {
//        editAccount.setBackgroundColor(getResources().getColor(R.color.login_background));
        String account = editAccount.getText().toString();
        register.setAccount(account);
        register.checkIfRegisted();
    }

    private void spin(View v, boolean start) {
    }

    private void passwordMatch() {
        String password = editPassword.getText().toString();
        String verifyPassword = this.verifyPassword.getText().toString();
        if (!verifyPassword.equals("")) {
            if (!password.equals(verifyPassword)) {
                checkIfRepasswordLabel.setVisibility(View.GONE);
            } else {
                checkIfRepasswordLabel.setVisibility(View.VISIBLE);
            }
        }
    }

    private void pressSubmitInfo(View v) {
        String account = editAccount.getText().toString();
        String password = editPassword.getText().toString();
        String verifyPassword = this.verifyPassword.getText().toString();
        if (account.equals("")) {
            Toast.makeText(this, "请输入账号", Toast.LENGTH_SHORT).show();
        } else if (password.equals("")) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
        } else if (verifyPassword.equals("")) {
            Toast.makeText(this, "请输入确认密码", Toast.LENGTH_SHORT).show();
        } else if (!verifyPassword.equals(password)) {
            Toast.makeText(this, "认证密码不正确", Toast.LENGTH_SHORT).show();
        } else if ((step2Title.getText().toString()).equals("账号已经被使用")) {
            Toast.makeText(this, "账号已经使用，请重新填写", Toast.LENGTH_SHORT).show();
        } else {
            register.setAccount(account);
            register.setPassword(password);
            step2.setVisibility(View.GONE);
            if (!chooseTarget) {
                step2.setVisibility(View.GONE);
                step3forPatriarch.setVisibility(View.VISIBLE);
            } else {
                step2.setVisibility(View.GONE);
                step3forTeacher.setVisibility(View.VISIBLE);
            }
            //初始化班级列表
            UserModel.getClassesList(mHandler);
            UserModel.getSubjectsList(mHandler);
        }
    }

    //页面三事件
    private void pressMyIcon(View v) {
        getPhotoFromAlbum(self);
    }

    private void pressChooseMan(View v) {
        v.setBackgroundColor(getResources().getColor(R.color.main_background));
        pChooseWoman.setBackgroundColor(getResources().getColor(R.color.transparent));
        tChooseWoman.setBackgroundColor(getResources().getColor(R.color.transparent));
        this.chooseSalutation = false;
    }

    private void pressChooseWomen(View v) {
        v.setBackgroundColor(getResources().getColor(R.color.main_background));
        pChooseMan.setBackgroundColor(getResources().getColor(R.color.transparent));
        tChooseMan.setBackgroundColor(getResources().getColor(R.color.transparent));
        this.chooseSalutation = true;
    }

    private void pressSubmitPDetail(View v) {
        String name = editPName.getText().toString();
        String contact = editPName.getText().toString();
        String childName = editPChildName.getText().toString();
        String guardian = editPGuardian.getText().toString();
        if (name.equals("")) {
            Toast.makeText(this, "请输入姓名", Toast.LENGTH_SHORT).show();
        } else if (contact.equals("")) {
            Toast.makeText(this, "请输入联系方式", Toast.LENGTH_SHORT).show();
        } else if (childName.equals("")) {
            Toast.makeText(this, "请输入孩子的姓名", Toast.LENGTH_SHORT).show();
        } else if (cid.equals("")) {
            Toast.makeText(this, "请输入孩子的班级", Toast.LENGTH_SHORT).show();
        } else if (!NetWorkUtil.getAvailableNetWorkInfo(self)) {
            Toast.makeText(self, "网络超时，请检查您的网络状态", Toast.LENGTH_SHORT).show();
        } else {
            register.setType("1");
            register.setName(name);
            register.setPhone(contact);
            register.setDescription(childName);
            register.setRole(guardian);
            register.setClassid(cid);
            register.setSex(chooseSalutation ? "2" : "1");
            register.setPhone(contact);
            register.submit();
            showReflashDialog("提交信息中");
        }
    }

    private void pressSubmitTDetail(View v) {
        String name = editTName.getText().toString();
        String contact = editTContact.getText().toString();
        String role = editTPost.getText().toString();
        String description = sid;
        if (name.equals("")) {
            Toast.makeText(this, "请输入姓名", Toast.LENGTH_SHORT).show();
        } else if (contact.equals("")) {
            Toast.makeText(this, "请输入联系方式", Toast.LENGTH_SHORT).show();
        } else if (role.equals("")) {
            Toast.makeText(this, "请输入您的职务", Toast.LENGTH_SHORT).show();
        } else if (cid.equals("")) {
            Toast.makeText(this, "请选择您的班级", Toast.LENGTH_SHORT).show();
        } else if (description.equals("")) {
            Toast.makeText(this, "请选择您的教学科目", Toast.LENGTH_SHORT).show();
        } else {
            register.setType("2");
            register.setName(name);
            register.setPhone(contact);
            register.setDescription(description);
            register.setRole(role);
            register.setClassid(cid);
            register.setSex(chooseSalutation ? "2" : "1");
            register.setPhone(contact);
            register.submit();
            showReflashDialog("提交信息中");
        }
    }

    private void chooseClass() {
        spinnerPChildClass.setDrawingCacheBackgroundColor(getResources().getColor(R.color.hint));
        spinnerTClass.setDrawingCacheBackgroundColor(getResources().getColor(R.color.hint));
        spinnerPChildClass.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cid = cids.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(self, "请选择一个班级", Toast.LENGTH_SHORT).show();
            }
        });

        spinnerTClass.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                cid = cids.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(self, "请选择一个班级", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void chooseSubject() {
        spinnerTSubject.setDrawingCacheBackgroundColor(getResources().getColor(R.color.hint));
        spinnerTSubject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                sid = sids.get(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(self, "请选择你的科目", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //調用SystemAlbumModule,從相冊獲取圖片
    public boolean getPhotoFromAlbum(Activity app) {
        try {
            Intent intent = new Intent(app, SystemAlbumActivity.class);
            app.startActivityForResult(intent, SystemConstant.GET_PHOTO_FROM_ALBUM);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    //Activity回调，接收从上一个Activity返回的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SystemConstant.GET_PHOTO_FROM_ALBUM:
                    url = data.getStringExtra("album");
                    File file = new File(url);
                    Bitmap bitmap = ImageUtil.getBitmapByFilePath(url);
                    register.setIconUrl(StorageUtil.copyAsImage(url, register.getAccount()));
                    editPMyIcon.setImageBitmap(bitmap);
                    if (file.exists())
                        if (NetWorkUtil.getAvailableNetWorkInfo(self))
                            UpdataUtil.uploadFile(file, file.getName(), true, mHandler);
                        else
                            Toast.makeText(self, "上传失败，请检查你的网络状态", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 显示刷新的时候的等待进度条
     */
    private void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(true);
        this.pd.setMessage(msg);
        this.pd.show();
    }

    /**
     * 显示刷新的时候的等待菊花
     */
    private void showMum(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(true);
        this.pd.setMessage(msg);
        this.pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                UpdataUtil.stop();
            }
        });
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */
    private void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
